package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.kh.KHDBConfig
import cn.com.kh.KHUtil
import cn.com.ph.WorkorderStepFix
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.text.SimpleDateFormat

/**
 * @projectName: ngsapitask-v3
 * @package: cn.com
 * @className: apiReceiveMonitor
 * @author: LiJT
 * @description: 通过接口方式定时生成接待效率数据
 * @date: 2022-09-29 13:21
 * @version: 1.0
 */

public class apiFixWorkorderStep implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiFixWorkorderStep.class);
    long startTime = System.currentTimeMillis();
    long endTime = System.currentTimeMillis();

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        JSONObject outData = JSONObject.fromObject("{\"code\":1,\"msg\":\"操作成功\"}");

        // 调用IP过滤
        if (KHDBConfig.getParam(eliteBean, "#APIIP") == "1" && !KHUtil.getRemoteHost(request)) {
            outData.put("code", -1);
            outData.put("message", "API被非法IP调用-Request Not Allow!");
            log.warn(outData);
            return outData;
        }

        String getMethod = request.getMethod();
        log.debug("HTTP请求调用类型 getMethod:" + getMethod);
        if (getMethod != "POST" && getMethod != "GET") {
            outData.put("code", -1);
            outData.put("message", "HTTP请求调用类型错误，接口调用失败：" + getMethod);
            log.error(outData);
            return outData;
        }

        // 获取所有Header
        Map<String, String> mapHeader = new HashMap<String, String>();
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            log.debug("Call Header-" + key + ":" + value);

            mapHeader.put(key, value);
        }

        // 获取所有参数名
        Map<String, String> mapParam = new HashMap<String, String>();
        Enumeration ep = request.getParameterNames();
        while (ep.hasMoreElements()) {
            String key = (String) ep.nextElement();
            String value = request.getParameter(key);
            log.debug("Call Parameter-" + key + ":" + value);
            mapParam.put(key, value);

        }

        // 获取调用数据
        String Syncpram = "";
        if (getMethod.equals("GET")) {
            Syncpram = request.getQueryString();
            log.info("接收调用GET参数信息：" + Syncpram);
        } else if (getMethod.equals("POST")) {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            BufferedReader iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                Syncpram += line;
            }
            log.info("接收调用POST报文信息：" + System.getProperty("line.separator") + Syncpram);
        }

        try {

            // 获取数据源List<Map<String, Object>>
            JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

            // 创建日期格式对象并设置要输出的格式
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

            // 获取接口调用时间参数
            String StartTime = request.getParameter("StartTime");
            String EndTime = request.getParameter("EndTime");
            log.debug("获取接口调用时间参数 API StartTime:" + StartTime + " EndTime:" + EndTime);

            // 初始化默认时间
            Calendar currDate = Calendar.getInstance();
            currDate.add(Calendar.DATE, 1);
            String EndTimeDefault = sdf.format(currDate.getTime());
            currDate.add(Calendar.DATE, -3);
            String StartTimeDefault = sdf.format(currDate.getTime());

            // 预处理加工数据开始&结束时间
            StartTime = KHUtil.isNull(StartTime) ? StartTimeDefault : StartTime;
            EndTime = KHUtil.isNull(EndTime) ? EndTimeDefault : EndTime;
            log.debug("预处理加工数据开始&结束时间 StartTime:" + StartTime + " EndTime:" + EndTime);

            // 接待效率数据处理
            int res_Num = WorkorderStepFix.doFixWorkorderStep(jt, StartTime, EndTime);
            log.debug("1-工单超时时间汇总处理...Result:" + res_Num);

            outData.put("data", res_Num);
            outData.put("msg", "预处理加工数据开始&结束时间 StartTime:" + StartTime + " EndTime:" + EndTime);

        } catch (Exception e) {
            outData.put("code", -1);
            outData.put("msg", "HTTP请求调用错误，接口处理异常：" + e.getMessage());
            log.error(outData, e);

        }
        return outData;
    }
}
